
<template>
  <div class="map-container">
    <el-dialog title="坐标拾取" :visible="visible" width="800px"  @close="dialogVisible=false">
      <div class="map-header">
        <el-input v-model="searchText" placeholder="输入地址搜索" style="width:300px"/>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="centerToCurrent">定位到当前位置</el-button>
      </div>

      <div class="map-wrapper">
        <div id="mapContainer" style="width:100%;height:500px"></div>
      </div>

      <div class="map-footer">
        <span>当前坐标：{{ currentPos.lat.toFixed(6) }}, {{ currentPos.lng.toFixed(6) }}</span>
        <el-button type="primary" @click="handleConfirm">确认选择</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLocation } from "@/api/system/map";
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'

export default {
  props: {
    visible: Boolean,
    defaultPos: {
      type: Object,
      default: () => ({ lat: 39.9042, lng: 116.4074 })
    },
    center: { type: Object, default: () => ({ lat: 39.9042, lng: 116.4074 }) },
    zoom: { type: Number, default: 13 },
    apiKey: { type: String, required: true }
  },
  onReady(){
    console.log("onReady")
    this.initMap()
  },
  data() {
    return {
      dialogVisible: false,
      isScriptLoaded: false,
      searchText: '',
      currentPos: { lat: 0, lng: 0 },
      map: null,
      marker: null,
      geocoder: null
    };
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
      if (val) this.$nextTick(this.initMap);
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  mounted() {
    console.log("mounted")

    fetch('https://map.qq.com/api/gljs?v=2.exp&key=UVQBZ-JMQ6M-OIB6V-6KTZH-CZYFF-Z2BIX&callback=initMap')
      .then(res => console.log('请求成功'))
      .catch(err => console.error('请求被拒绝，请检查白名单', err));

    this.loadMapScript()
      .then(() => {
        this.isScriptLoaded = true
        const checkInterval = setTimeout(() => {
          console.log("setInterval")
          this.initMap()
          if (window.TMap ) {
            clearInterval(checkInterval)
            resolve()
          }
        }, 2000)

      })
      .catch(err => {
        console.error('地图加载失败:', err)
        this.$emit('error', err)
      })
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    loadMapScript() {
      return new Promise((resolve, reject) => {
        if (window.TMap ) {
          resolve()
          return
        }

        const script = document.createElement('script')
        script.src = `https://map.qq.com/api/gljs?v=2.exp&key=${this.apiKey}&callback=initMap`
        script.async = true; // 异步加载
        script.defer = true;
        console.log("script.src")
        console.log(script.src)
        script.onload = () => {
          // 腾讯地图需要额外检查TMap对象
          // const checkInterval = setTimeout(() => {
          //   console.log("setInterval")
          //   if (window.TMap ) {
          //     clearInterval(checkInterval)
          //     resolve()
          //   }
          // }, 2000)
          this.initMap()
        }
        script.onerror = reject
        document.head.appendChild(script)
      })
    },

    // loadMapScript() {
    //   return new Promise((resolve) => {
    //     if (window.qq && window.qq.maps) {
    //       resolve()
    //       return
    //     }
    //
    //     window.initMap = resolve
    //     const script = document.createElement('script')
    //     script.src = `https://map.qq.com/api/gljs?v=2.exp&key=${this.apiKey}&callback=initMap`
    //     document.head.appendChild(script)
    //   })
    // },
    initMap() {

      // 验证容器元素是否存在
      if (!document.getElementById('mapContainer')) {
        throw new Error('地图容器元素不存在');
      }
      if (!this.isScriptLoaded) return
      const center = new Window.TMap.LatLng(this.center.lat, this.center.lng)
      this.map = new Window.TMap.Map(this.$refs.mapContainer, {
        center,
        zoom: this.zoom
      })
    },


    // initMap() {
    //   const script = document.createElement('script');
    //   script.src = `https://map.qq.com/api/js?v=2.exp&key=UVQBZ-JMQ6M-OIB6V-6KTZH-CZYFF-Z2BIX&libraries=geocoder`;
    //   script.async = true; // 异步加载
    //   script.defer = true;
    //   document.head.appendChild(script);
    //   script.onload = () => {
    //     // 确保qq.maps对象已存在
    //     if(typeof qq !== 'undefined' && qq.maps) {
    //       this.map = new qq.maps.Map(document.getElementById("mapContainer"), {
    //         center: new qq.maps.LatLng(this.defaultPos.lat, this.defaultPos.lng),
    //         zoom: 15
    //       });
    //     }else {
    //       console.log("地图加载失败")
    //     }
    //
    //
    //     this.geocoder = new qq.maps.Geocoder();
    //     this.marker = new qq.maps.Marker({ map: this.map });
    //
    //     qq.maps.event.addListener(this.map, 'click', (event) => {
    //       const latLng = event.latLng;
    //       this.currentPos = { lat: latLng.getLat(), lng: latLng.getLng() };
    //       this.marker.setPosition(latLng);
    //     });
    //
    //     this.centerToCurrent();
    //   };
    //
    // },
    centerToCurrent() {
      getLocation().then(res => {
        const pos = new qq.maps.LatLng(res.latitude, res.longitude);
        this.map.setCenter(pos);
        this.marker.setPosition(pos);
        this.currentPos = { lat: res.latitude, lng: res.longitude };
      });
    },
    handleSearch() {
      this.geocoder.getLocation(this.searchText, (res) => {
        if (res.detail && res.detail.location) {
          const pos = new qq.maps.LatLng(res.detail.location.lat, res.detail.location.lng);
          this.map.setCenter(pos);
          this.marker.setPosition(pos);
          this.currentPos = { lat: pos.getLat(), lng: pos.getLng() };
        }
      });
    },
    handleConfirm() {
      this.$emit('confirm', this.currentPos);
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped>
.map-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}
.map-container{
  height: 600px;
  width: 100%;
}
.map-footer {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
